const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
app.listen(3000);
const svg = require('svg-captcha');
const session = require('cookie-session')

// 中间件
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(session({
    keys: ['rfff', 'iiii'],
}))
app.get('/code', (req, res) => {
    let captcha = svg.create({
        size: 4,
        ignoreChars: 'oOiI1lL',
        color: true,
        noise: 3,
        background: '#ccc'
    })
    req.session.yzm = captcha.text;
    console.log(captcha.text);
    res.type('svg');
    res.send(captcha.data);

})
// 引入并使用mysql模块
const mysql = require('mysql');
let con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: 3306,
    database: 'demo'
})
con.connect();

// 渲染页面
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, '注册.html'))
})


// 注册逻辑
app.post('/register', (req, res, next) => {
    console.log(req.session.yzm);
    let { tel, pass, pass2, yzm } = req.body;
    // console.log(tel, pass, pass2, yzm);
    // 验证码

    if (!yzm) {
        next('验证码为空');
        return;
    }
    // console.log(yzm);

    if (req.session.yzm != yzm) {
        next('验证码输入有误');
        return;
    }
    // 传参不能为空
    if (!tel || !pass || !pass2) {
        next('请输入有效内容');
        return;
    }
    // 判断两次密码是否一致
    if (pass != pass2) {
        next('两次密码输入不一致');
        return;
    }
    // 判断是否存在

    function fn() {
        return new Promise((resolve, reject) => {
            let is = `SELECT * FROM 已有用户 WHERE username='${tel}'`;
            con.query(is, (err, result) => {
                if (err) {
                    next(err)
                    return;
                }
                if (result.length > 0) {
                    next('用户名已存在')
                    return;
                }
                resolve({ tel, pass })
            })
        })
    }
    // 用户名不存在可注册
    async function shi() {
        let { tel, pass } = await fn();
        let sqr = `INSERT INTO 已有用户 (username,password) VALUES ('${tel}','${pass}')`;
        con.query(sqr, (err, result) => {
            if (err) {
                next(err)
                return;
            }
            if (result.affectedRows > 0) {
                next('注册成功')
                return;
            }
        })
    }
    shi();

})

app.use((err, req, res, next) => {
    res.send({ code: 400, msg: err })
})


